
package lt.andro.seimorinkimai2012;

import lt.andro.utils.GoogleAnalyticsEventsHelper;

import org.jsoup.select.Elements;

import android.app.Activity;
import android.os.AsyncTask;
import android.util.Log;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class SrWebViewClient extends WebViewClient {

    protected static final String TAG = SrWebViewClient.class.getCanonicalName();
    private final Activity mActivity;
    private final GoogleAnalyticsEventsHelper mGoogleAnalyticsEventsHelper;
    private AsyncTask<String, Void, Elements> mPageLoaderTask;

    public SrWebViewClient(Activity activity,
            GoogleAnalyticsEventsHelper googleAnalyticsEventsHelper, WebView view) {
        mActivity = activity;
        this.mGoogleAnalyticsEventsHelper = googleAnalyticsEventsHelper;
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        Log.d(TAG, url);
        cancelIfInProgress();
        mPageLoaderTask = new WebPageLoaderTask(view, mActivity, mGoogleAnalyticsEventsHelper)
                .execute(url);
        return true;
    }

    public void onPause() {
        cancelIfInProgress();
    }

    private void cancelIfInProgress() {
        if (mPageLoaderTask != null) {
            if (mPageLoaderTask.getStatus() != AsyncTask.Status.FINISHED) {
                mPageLoaderTask.cancel(true);
            }
        }
    }
}
